import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import { Form, Button, Select, Upload, Input, Divider, Icon, Row, Col, message, Spin, Modal } from 'antd'
import PropTypes from 'prop-types'

import ContentBox from 'components/contentBox'
import Style from './details.css'

const { Option } = Select
const { TextArea } = Input
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 }
}
class details extends Component {
  static propTypes = {
    form: PropTypes.any,
    getAuthorList: PropTypes.func,
    authorOptionsList: PropTypes.any,
    addStore: PropTypes.func,
    goodsDetails: PropTypes.any,
    getGoodsDetails: PropTypes.func,
    match: PropTypes.any,
    addStoreRequest: PropTypes.func,
    editRequest: PropTypes.func,
    editGoods: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {
      imageList: []
    }
    this.handleEdit = this.handleEdit.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.firstImageChange = this.firstImageChange.bind(this)
    this.onChange = this.onChange.bind(this)
    this.showAdd = this.showAdd.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.priceChange = this.priceChange.bind(this)
  }

  showAdd () {
    this.setState({
      showAdd: true
    })
  }

  handleCancel () {
    this.setState({
      showAdd: false
    })
  }

  handleOk () {
    const { getFieldValue } = this.props.form
    if (!getFieldValue('addStock')) {
      message.error('请输入库存')
    } else {
      this.props.addStore({
        stock: getFieldValue('addStock'),
        commodityId: this.id
      })
    }

    // this.props.form.validateFieldsAndScroll((err, values) => {
    //   if (!values.addStock) {
    //     this.props.addStore({
    //       stock: values['addStock'],
    //       commodityId: this.id
    //     })
    //   } else {

    //   }
    // })
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 64
    if (!isLt2M) {
      message.error('图片大小 64MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  baseTypeChange (value) {
    this.setState({
      baseType: value
    })
  }

  firstImageChange ({ file, fileList, event }) {
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      message.error('上传失败')
      this.setState({
        loading: false
      })
      return
    }

    if (file.status === 'done') {
      this.setState({
        loading: false,
        coverImg: {
          imageUrl: file.response && file.response.data.imageUrl,
          width: file.response && file.response.data.width,
          height: file.response && file.response.data.height
        }
      })
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  onChange ({ file, fileList, event }) {
    let imageArr = []
    const { imageList } = this.state
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      this.setState({
        loading: false
      })
      message.error('上传失败')
    }

    if (file.status === 'done') {
      imageArr.push({
        imageUrl: file.response && file.response.data.imageUrl,
        width: file.response && file.response.data.width,
        height: file.response && file.response.data.height
      })

      this.setState({
        loading: false,
        imageList: imageArr.concat(imageList)
      })
    }
    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  handleClose (index) {
    const { imageList } = this.state
    const imageCp = imageList.slice(0, imageList.length)
    imageCp.splice(index, 1)
    this.setState({
      imageList: imageCp
    })
  }

  componentDidMount () {
    const { id } = this.props.match.params
    this.id = id
    this.props.getGoodsDetails({
      commodityId: id
    })
    this.props.getAuthorList()
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.goodsDetails && nextProps.goodsDetails) {
      this.setState({
        imageList: nextProps.goodsDetails && nextProps.goodsDetails.imageList,
        coverImg: nextProps.goodsDetails && nextProps.goodsDetails.coverImg
      })
    }

    if (!this.props.editRequest && nextProps.editRequest) {
      message.success('编辑成功')
      setTimeout(() => {
        window.location.href = '/goods/list'
      }, 800)
    }

    if (!this.props.addStoreRequest && nextProps.addStoreRequest) {
      message.success('新增成功')
      setTimeout(() => {
        this.setState({
          showAdd: false
        })
        location.reload()
      }, 700)
    }
  }

  priceChange (e) {
    const { setFieldsValue } = this.props.form
    const { value } = e.target
    setTimeout(() => {
      setFieldsValue({
        price: (value === '' || value === 'NaN') ? null : parseFloat(value.replace(/,/g, '')).replace(/\d(?=(?:\d{3})+\b)/g, '$&,')
      })
    }, 50)
  }

  handleEdit () {
    const { coverImg, imageList } = this.state
    const { goodsDetails } = this.props
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.keys) {
          values.keys = values.keys.split(' ')
        }

        if (values.price) {
          values.price = parseFloat(values.price.replace(/,/g, '')) * 100
        }
        values.codePath = goodsDetails.codePath
        values.categoryCode = goodsDetails.categoryCode
        values.categoryName = goodsDetails.categoryName
        values.id = this.id
        values.integration = goodsDetails.integration
        values.namePath = goodsDetails.namePath
        values.coverImg = coverImg
        values.imageList = imageList
        // values.baseType = goodsDetails.baseType
        values.attributeInfo = {
          fit: values.fit,
          material: values.material,
          specInfo: values.specInfo,
          year: values.year
        }
        delete values.fit
        delete values.material
        delete values.specInfo
        delete values.year
        values.addStock && delete values.addStock
        this.props.editGoods(values)
      }
    })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { status } = this.props.match.params
    const { imageList, coverImg, loading, showAdd, baseType } = this.state
    const { goodsDetails, authorOptionsList = [] } = this.props

    const uploadButton = (
      <div className={Style[`${coverImg ? '' : 'image-container'}`]}>
        {
          coverImg ? <img className={Style['image']} src={coverImg.imageUrl} /> : <>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className={Style['ant-upload-text']}>Upload</div></>
        }
      </div>
    )
    return (
      <>
        <ContentBox>
          <Spin spinning={!goodsDetails}>
            <div className={Style['details-container']}>
              <Row gutter={24}>
                <Col span={18}>
                  <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                    <Form.Item label='商品分类' colon={false} style={{ fontSize: '16px' }} />

                    <Form.Item label='商品类别' >
                      {getFieldDecorator('namePath', {
                        initialValue: goodsDetails && goodsDetails.namePath,
                        rules: [{ required: true, message: '请输入!' }]
                      })(
                        <Input placeholder='请输入' disabled />
                      )}
                    </Form.Item>
                    <Divider />
                    <Form.Item label='基本信息' colon={false} style={{ fontSize: '16px' }} />

                    <Row gutter={24}>
                      <Col span={12}>
                        <Form.Item label='商品名称' labelCol={{ span: 5, offset: 3 }}>
                          {getFieldDecorator('name', {
                            initialValue: goodsDetails && goodsDetails.name,
                            rules: [{ required: true, message: '请输入商品名称!' }]
                          })(
                            <Input placeholder='请输入商品名称' disabled={status === 'details'} />
                          )}
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item label='创作者' labelCol={{ span: 5 }}>
                          {getFieldDecorator('authorId', {
                            initialValue: goodsDetails && goodsDetails.authorId,
                            rules: [
                              { required: true, message: '请选择创作者!' }
                            ]
                          })(
                            <Select placeholder='请选择创作者' disabled={status === 'details'}>
                              {
                                authorOptionsList && authorOptionsList.map((item, index) => <Option key={index} value={item.authorId}>{item.authorName}</Option>)
                              }
                            </Select>
                          )}
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={24}>
                      <Col span={12}>
                        <Form.Item label='运费模板' labelCol={{ span: 5, offset: 3 }}>
                          {getFieldDecorator('templeteId', {
                            initialValue: goodsDetails && goodsDetails.templeteId,
                            rules: [
                              { required: true, message: '请选择运费模板!' }
                            ]
                          })(
                            <Select placeholder='请选择运费模板' disabled={status === 'details'}>
                              <Option value='default'>默认运费模板</Option>
                            </Select>
                          )}
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item label='商品积分' labelCol={{ span: 5 }}>
                          {getFieldDecorator('integration', {
                            initialValue: goodsDetails && goodsDetails.integration,
                            rules: [
                              { required: true, message: '请输入商品积分' }
                            ]
                          })(
                            <Input placeholder='请输入商品积分' disabled />
                          )}
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={24}>
                      <Col span={12}>
                        <Form.Item label='商品编号' labelCol={{ span: 5, offset: 3 }}>
                          {getFieldDecorator('commodityCode', {
                            initialValue: goodsDetails && goodsDetails.commodityCode,
                            rules: [{ required: true }]
                          })(
                            <Input placeholder='请输入' disabled={status === 'details' || status === 'edit'} />
                          )}
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item label='商品货号' labelCol={{ span: 5 }}>
                          {getFieldDecorator('commodityNo', {
                            initialValue: goodsDetails && goodsDetails.commodityNo,
                            rules: [{ required: true }]
                          })(
                            <Input placeholder='请输入' disabled={status === 'details' || status === 'edit'} />
                          )}
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={24}>
                      <Col span={12}>
                        <Form.Item label='基本类型' labelCol={{ span: 5, offset: 3 }}>
                          {getFieldDecorator('baseType', {
                            initialValue: (goodsDetails && goodsDetails.baseType) || 1,
                            rules: [{ required: true, message: '请选择' }]
                          })(
                            <Select placeholder='请选择' onChange={this.baseTypeChange} disabled={status === 'details'}>
                              <Option value={1}>作品</Option>
                              <Option value={2}>标品</Option>
                            </Select>
                          )}
                        </Form.Item>
                      </Col>
                      <Col span={12} />
                    </Row>
                    <Row gutter={24}>
                      <Col span={12}>
                        <Form.Item label='商品价格' labelCol={{ span: 5, offset: 3 }}>
                          {getFieldDecorator('price', {
                            initialValue: goodsDetails && goodsDetails.price && (goodsDetails.price / 100).toLocaleString(),
                            rules: [{ required: true, message: '请输入商品价格!' }
                            // {
                            //   validator: (rule, value, callback) => {
                            //     if (/^[0-9]+\.?[0-9]{0,2}$/.test(Number(value))) {
                            //       callback()
                            //     } else {
                            //       try {
                            //         throw new Error('请输入正确的金额（最小精度为分）')
                            //       } catch (err) {
                            //         callback(err)
                            //       }
                            //     }
                            //   }
                            // }
                            ]
                          })(
                            <Input placeholder='请输入商品价格' disabled={status === 'details'} onChange={this.priceChange} />
                          )}
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item label='商品库存' labelCol={{ span: 5 }}>
                          {getFieldDecorator('stock', {
                            initialValue: goodsDetails && goodsDetails.stock,
                            rules: [{ required: true, message: '请输入商品库存!' }]
                          })(
                            <Input className={Style['store']} placeholder='请输入商品库存' disabled={status === 'details'} />
                          )}
                        </Form.Item>
                        {
                          status === 'edit' && (baseType === 2 || (goodsDetails && goodsDetails.baseType === 2)) && <Button type='primary' className={Style['add-store']} onClick={this.showAdd}>
                            新增库存
                          </Button>
                        }
                      </Col>
                    </Row>
                    <Form.Item label='商品类型'>
                      {getFieldDecorator('comType', {
                        initialValue: goodsDetails && goodsDetails.comType,
                        rules: [{ required: true, message: '请选择!' }]
                      })(
                        <Select placeholder='请选择' disabled={status === 'details'}>
                          {/* <Option value='NEW_PRODUCT'>新品</Option>
                          <Option value='HOT_SALE'>热销</Option> */}
                          <Option value='PERSONAGE'>人物</Option>
                          <Option value='SCENERY'>景物</Option>
                          <Option value='STILL_LIFE'>静物</Option>
                          <Option value='ABSTRACT_PAINTING'>抽象</Option>
                        </Select>
                      )}
                    </Form.Item>
                    <Form.Item label='商品描述'>
                      {getFieldDecorator('profile', {
                        initialValue: goodsDetails && goodsDetails.profile,
                        rules: [{ required: true, message: '请输入商品描述!' }]
                      })(
                        <TextArea placeholder='请输入商品描述' rows={8} disabled={status === 'details'} />
                      )}
                    </Form.Item>
                    <Form.Item label='商品关键字'>
                      {getFieldDecorator('keys', {
                        initialValue: goodsDetails && goodsDetails.keys && goodsDetails.keys.join(' ')
                        // rules: [{ required: true, message: '请输入商品关键字!' }]
                      })(
                        <TextArea placeholder='请输入商品关键字' rows={8} disabled={status === 'details'} />
                      )}
                    </Form.Item>
                    <Form.Item label='商品备注'>
                      {getFieldDecorator('memo', {
                        initialValue: goodsDetails && goodsDetails.memo
                        // rules: [{ required: true, message: '请输入商品备注!' }]
                      })(
                        <TextArea placeholder='请输入商品备注' rows={8} disabled={status === 'details'} />
                      )}
                    </Form.Item>
                    <Divider />
                    <Form.Item label='商品属性' colon={false} style={{ fontSize: '16px' }} />

                    <Form.Item label='创作年份' >
                      {getFieldDecorator('year', {
                        initialValue: goodsDetails && goodsDetails.attributeInfo && goodsDetails.attributeInfo.year,
                        rules: [{ required: true, message: '请输入创作年份!' }]
                      })(
                        <Input placeholder='请输入创作年份' disabled={status === 'details'} />
                      )}
                    </Form.Item>
                    <Form.Item label='材料' >
                      {getFieldDecorator('material', {
                        initialValue: goodsDetails && goodsDetails.attributeInfo && goodsDetails.attributeInfo.material,
                        rules: [{ required: true, message: '请输入材料!' }]
                      })(
                        <Input placeholder='请输入材料' disabled={status === 'details'} />
                      )}
                    </Form.Item>
                    <Form.Item label='规格' >
                      {getFieldDecorator('specInfo', {
                        initialValue: goodsDetails && goodsDetails.attributeInfo && goodsDetails.attributeInfo.specInfo,
                        rules: [{ required: true, message: '请输入规格!' }]
                      })(
                        <Input placeholder='请输入规格' disabled={status === 'details'} />
                      )}
                    </Form.Item>
                    <Form.Item label='适用' >
                      {getFieldDecorator('fit', {
                        initialValue: goodsDetails && goodsDetails.attributeInfo && goodsDetails.attributeInfo.fit
                        // rules: [{ required: true, message: '请输入适用!' }]
                      })(
                        <Input placeholder='请输入适用' disabled={status === 'details'} />
                      )}
                    </Form.Item>
                    <Divider />
                    <Form.Item label='商品封面' colon={false} style={{ fontSize: '16px' }} />

                    <Form.Item wrapperCol={{ span: 12, offset: 4 }}>
                      <Upload
                        action='/file/upload/1.0'
                        name='file'
                        beforeUpload={this.beforeUpload}
                        onChange={this.firstImageChange}
                        showUploadList={false}
                        withCredentials
                        headers={{
                          token: localStorage.getItem('token') || ''
                        }}
                      >
                        {uploadButton}
                        {
                          status === 'edit' && <Button style={{ marginTop: '20px' }}>
                            <Icon type='upload' /> 选择上传图片
                          </Button>
                        }
                      </Upload>
                    </Form.Item>
                    <Form.Item label='商品相册' colon={false} style={{ fontSize: '16px' }} />

                    <Form.Item wrapperCol={{ span: 12, offset: 4 }}>
                      <div className={Style['image-list']}>
                        {
                          imageList && imageList.map((item, index) => <div key={index} className={Style['image-container']}>
                            {
                              status === 'edit' && <Icon type='close-circle' className={Style['close']} onClick={() => this.handleClose(index)} />
                            }
                            <img className={Style['image']} src={item.imageUrl} />
                          </div>)
                        }
                      </div>
                    </Form.Item>
                    {
                      status === 'edit' && <Form.Item wrapperCol={{ span: 12, offset: 4 }} help='按住ctrl可同时批量选择多张图片上传，最多可以上传5张图片，封面图片限定尺寸900:600' style={{ marginTop: '-24px' }}>
                        <Upload
                          action='/file/upload/1.0'
                          name='file'
                          onChange={this.onChange}
                          showUploadList={false}
                          withCredentials
                          headers={{
                            token: localStorage.getItem('token') || ''
                          }}
                        >
                          <Button type='primary'>
                            <Icon type='cloud-upload' /> 选择上传图片
                          </Button>
                        </Upload>
                      </Form.Item>
                    }
                    {
                      status === 'edit' && <div className={Style['btn-container']}>
                        <Button type='primary' onClick={this.handleEdit}>
                          修改商品信息
                        </Button>
                      </div>
                    }
                  </Form>
                </Col>
              </Row>
            </div>
          </Spin>
          <Modal
            title='新增库存'
            visible={showAdd}
            width={600}
            onOk={this.handleOk}
            destroyOnClose
            onCancel={this.handleCancel}
          >
            <Form {...formItemLayout}>
              <Form.Item label='库存'>
                {getFieldDecorator('addStock')(
                  <Input placeholder='请输入' type='number' />
                )}
              </Form.Item>
            </Form>
          </Modal>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  goodsDetails: state.goods.goodsDetails,
  authorOptionsList: state.goods.authorOptionsList,
  editRequest: state.goods.editRequest,
  addStoreRequest: state.goods.addStoreRequest
})
const mapDispatch = dispatch => ({
  getGoodsDetails: dispatch.goods.getGoodsDetails,
  getAuthorList: dispatch.goods.getAuthorList,
  editGoods: dispatch.goods.editGoods,
  addStore: dispatch.goods.addStore
})
const Formdetails = Form.create()(details)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Formdetails)
)
